package gdingtalk

import (
	"gitee.com/zjlsliupei/ghelp"
)

type Department struct {
}

func NewDepartment() Department {
	return Department{}
}

// GetAllSubDept 获取该部门下所有子部门，算法采用递归调用，注意部门嵌套深度
func (__ *Department) GetAllSubDept(corpId string, deptId int64) []map[string]interface{} {
	var depts []map[string]interface{}
	res := Post().
		AutoAccessToken(corpId).
		SetPath("/topapi/v2/department/listsub").
		AddBodyParam("dept_id", deptId).
		Do()
	if !res.IsSuccess() {
		return depts
	}
	if len(res.GetBody("result").Array()) < 1 {
		return depts
	}
	for _, v := range res.GetBody("result").Array() {
		depts = append(depts, ghelp.JsonDecode(v.Raw).(map[string]interface{}))
		_depts := __.GetAllSubDept(corpId, v.Get("dept_id").Int())
		if len(_depts) > 0 {
			depts = append(depts, _depts...)
		}
	}
	return depts
}
